#include "NetTools.h"
#include <iostream>
#include <arpa/inet.h>

NetTools::NetTools(/* args */)
{
}

NetTools::~NetTools()
{
}

ssize_t NetTools::dispatch(int socket, const char *ptr, size_t size, int flags)
{
    if (!ptr)
    {
        std::cerr << "ptr is null" << std::endl;
        return -1;
    }
    ssize_t bytes_sent;
    // 循环发送数据直到发送完所有数据
    size_t remaining = size;
    while (remaining > 0)
    {
        ssize_t bytes_sent = send(socket, ptr, remaining, flags);

        if (bytes_sent < 0)
        {
            if (errno == EINTR)
            {
                continue;
            }
            std::cerr << "send failed" << std::endl;
            return bytes_sent;
        }
        // 更新已发送数据的指针和剩余字节数
        ptr += bytes_sent;
        remaining -= bytes_sent;
    }
    return size;
}
ssize_t NetTools::receive(int socket, char *ptr, size_t size, int flags)
{
    if (!ptr)
    {
        std::cerr << "ptr is null" << std::endl;
        return -1;
    }
    size_t remaining = size;

    // 循环读取数据直到读取到指定大小的数据
    while (remaining > 0)
    {
        ssize_t bytes_read = recv(socket, ptr, remaining, flags);
        if (bytes_read < 0)
        {
            if (errno == EINTR)
            {
                continue;
            }
            std::cerr << "recv failed" << std::endl;
            return bytes_read;
        }
        // 更新已读取数据的指针和剩余字节数
        ptr += bytes_read;
        remaining -= bytes_read;
    }

    return size;
}

void NetTools::closeSocket(int &socket)
{
    if (-1 != socket)
    {
        close(socket);
        socket = -1;
    }
}
